package com.travelpass.fragments;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.travelpass.R;
import com.travelpass.slidingMenu.MainActivity;

@SuppressLint("ValidFragment")
public class HorairesTrain extends SherlockFragment {

	private View view;

	Spinner dep, arr;

	String depart = "ADDAKHLA(Supratours)", arrivee = "ADDAKHLA(Supratours)";

	LinearLayout tra;

	public HorairesTrain() {

	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.horairestrain, container, false);

		init();
		return view;

	}

	private void init() {
		dep = (Spinner) view.findViewById(R.id.dep);
		arr = (Spinner) view.findViewById(R.id.arr);
		MainActivity.villes = new ArrayList<String>();
		MainActivity.villes.add("ADDAKHLA(Supratours)");
		MainActivity.villes.add("AEROPORT Med V");
		MainActivity.villes.add("AGADIR(Supratours)");
		MainActivity.villes.add("AGDZ (SUPRAT.)(Supratours)");
		MainActivity.villes.add("AIN DEFALI (Supratours)");
		MainActivity.villes.add("AIN SEBAA");
		MainActivity.villes.add("AIN-TAOUJDATE");
		MainActivity.villes.add("ASILAH");
		MainActivity.villes.add("ASSA(Supratours)");
		MainActivity.villes.add("AZEMMOUR HALTE");
		MainActivity.villes.add("AZROU (SUPRAT.) (Supratours)");
		MainActivity.villes.add("BENGUERIR");
		MainActivity.villes.add("BENI NSAR PORT");
		MainActivity.villes.add("BENI NSAR villes");
		MainActivity.villes.add("BENI-MELLAL(Supratours)");
		MainActivity.villes.add("BERRECHID");
		MainActivity.villes.add("BIDANE");
		MainActivity.villes.add("BOUIZAKARNE(Supratours)");
		MainActivity.villes.add("BOUJAD (SUPRAT.)(Supratours)");
		MainActivity.villes.add("BOUJDOUR(Supratours)");
		MainActivity.villes.add("BOUMALNE(Supratours)");
		MainActivity.villes.add("BOUSKOURA");
		MainActivity.villes.add("BOUZNIKA");
		MainActivity.villes.add("CASA PORT");
		MainActivity.villes.add("CASA VOYAGEURS");
		MainActivity.villes.add("CHEFCHAOUEN (Supratours)");
		MainActivity.villes.add("DALIA");
		MainActivity.villes.add("DAR EL GUEDARI");
		MainActivity.villes.add("EL AIOUN");
		MainActivity.villes.add("El Argoub (Supra)(Supratours)");
		MainActivity.villes.add("EL HAJEB (SUPRAT.) (Supratours)");
		MainActivity.villes.add("EL JADIDA");
		MainActivity.villes.add("EL KSAR EL KEBIR");
		MainActivity.villes.add("ELKELAA MGOUNA(Supratours)");
		MainActivity.villes.add("ENNASSIM");
		MainActivity.villes.add("ENNOUASSER");
		MainActivity.villes.add("EOUFOUSS (SUPRAT.) (Supratours)");
		MainActivity.villes.add("ERFOUD (SUPRAT.) (Supratours)");
		MainActivity.villes.add("ERRACHIDIA (SUPRAT.) (Supratours)");
		MainActivity.villes.add("ERRICH (SUPRAT.) (Supratours)");
		MainActivity.villes.add("ESSAOUIRA(Supratours)");
		MainActivity.villes.add("FACULTES");
		MainActivity.villes.add("FES");
		MainActivity.villes.add("FNIDEQ (SUPRA.) (Supratours)");
		MainActivity.villes.add("Gargarate (Supra)(Supratours)");
		MainActivity.villes.add("GUELMIMA (Supratours)");
		MainActivity.villes.add("GUELMIME(Supratours)");
		MainActivity.villes.add("GUERCIF");
		MainActivity.villes.add("HASSI BERKANE");
		MainActivity.villes.add("INEZGANE(Supratours)");
		MainActivity.villes.add("JORF EL MELHA (Supratours)");
		MainActivity.villes.add("KASBAH TADLA (SUPRAT.)(Supratours)");
		MainActivity.villes.add("KELAA DES SRAGHNAS(Supratours)");
		MainActivity.villes.add("KENITRA");
		MainActivity.villes.add("KENITRA MEDINA");
		MainActivity.villes.add("KHENIFRA (SUPRAT.) (Supratours)");
		MainActivity.villes.add("KHENIFRA(Supratours)");
		MainActivity.villes.add("KHOURIBGA");
		MainActivity.villes.add("KHOURIBGA (SUPRAT.)(Supratours)");
		MainActivity.villes.add("kSAR SGHIR");
		MainActivity.villes.add("L'OASIS");
		MainActivity.villes.add("LAAYOUNE PORT(Supratours)");
		MainActivity.villes.add("LAAYOUNE(Supratours)");
		MainActivity.villes.add("LALLA YTO");
		MainActivity.villes.add("Lamhariz (Supra)(Supratours)");
		MainActivity.villes.add("MARRAKECH");
		MainActivity.villes.add("MARTIL(Supratours)");
		MainActivity.villes.add("MATMATA");
		MainActivity.villes.add("MDIQ (SUPRA.) (Supratours)");
		MainActivity.villes.add("MECHRA BEL KSIRI");
		MainActivity.villes.add("MEKNES");
		MainActivity.villes.add("MEKNES AL AMIR");
		MainActivity.villes.add("MELG EL OUIDANE");
		MainActivity.villes.add("MELLOUSSA 1");
		MainActivity.villes.add("MERS SULTAN");
		MainActivity.villes.add("MERZOUGA (SUPRAT.) (Supratours)");
		MainActivity.villes.add("MIDELT (SUPRAT.) (Supratours)");
		MainActivity.villes.add("MOHAMMEDIA");
		MainActivity.villes.add("MRIRT (SUPRAT.) (Supratours)");
		MainActivity.villes.add("NADOR SUD");
		MainActivity.villes.add("NADOR villes");
		MainActivity.villes.add("OUARZAZATE(Supratours)");
		MainActivity.villes.add("OUED AMLIL");
		MainActivity.villes.add("OUED ZEM");
		MainActivity.villes.add("OUED ZEM (SUPRAT.)(Supratours)");
		MainActivity.villes.add("OUELED RAHOU");
		MainActivity.villes.add("OUEZZANE (Supratours)");
		MainActivity.villes.add("OUJDA");
		MainActivity.villes.add("OULAD KHITIB");
		MainActivity.villes.add("Port Tanger Med(Supratours)");
		MainActivity.villes.add("RABAT AGDAL");
		MainActivity.villes.add("RABAT villes");
		MainActivity.villes.add("RAS EL AIN");
		MainActivity.villes.add("RISSANI (SUPRAT.) (Supratours)");
		MainActivity.villes.add("SAFI");
		MainActivity.villes.add("SAFI (SUPRAT.)(Supratours)");
		MainActivity.villes.add("SALE");
		MainActivity.villes.add("SALE TABRIQUET");
		MainActivity.villes.add("SEBAA-AIOUN");
		MainActivity.villes.add("SELOUANE");
		MainActivity.villes.add("SETTAT");
		MainActivity.villes.add("SIDI BOU OTHMANE");
		MainActivity.villes.add("SIDI EL AIDI");
		MainActivity.villes.add("SIDI HAJJAJ");
		MainActivity.villes.add("SIDI KACEM");
		MainActivity.villes.add("SIDI SLIMANE MEDINA");
		MainActivity.villes.add("SIDI YAHIA");
		MainActivity.villes.add("SKHIRAT");
		MainActivity.villes.add("SMARA(Supratours)");
		MainActivity.villes.add("SOUK EL ARBAA");
		MainActivity.villes.add("TAMANAR(Supratours)");
		MainActivity.villes.add("TAMELALT (SUPRAT.) (Supratours)");
		MainActivity.villes.add("TAN TAN PORT(Supratours)");
		MainActivity.villes.add("TAN TAN(Supratours)");
		MainActivity.villes.add("TANGER");
		MainActivity.villes.add("TAOURIRT");
		MainActivity.villes.add("TARFAYA(Supratours)");
		MainActivity.villes.add("TAZA");
		MainActivity.villes.add("Tchika (Supra)(Supratours)");
		MainActivity.villes.add("TEMARA");
		MainActivity.villes.add("TETOUAN(Supratours)");
		MainActivity.villes.add("TINERHIR(Supratours)");
		MainActivity.villes.add("TINJDAD (Supratours)");
		MainActivity.villes.add("TIZNIT(Supratours)");
		MainActivity.villes.add("TLETA RISSANA");
		MainActivity.villes.add("YOUSSOUFIA");
		MainActivity.villes.add("ZAG(Supratours)");
		MainActivity.villes.add("ZAGORA (SUPRAT.)(Supratours)");
		MainActivity.villes.add("ZAOUIAT CHEHCH (SUPRAT.)(Supratours)");

		MyAdapter adapter = new MyAdapter(MainActivity.villes);
		dep.setAdapter(adapter);
		arr.setAdapter(adapter);

		dep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				depart = (String) parent.getItemAtPosition(pos);
			}

			public void onNothingSelected(AdapterView parent) {
				// Do nothing.
			}
		});

		arr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			/**
			 * Called when a new item was selected (in the Spinner)
			 */
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				arrivee = (String) parent.getItemAtPosition(pos);
			}

			public void onNothingSelected(AdapterView parent) {
				// Do nothing.
			}
		});

		((Button) view.findViewById(R.id.trouver)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (depart.equals(arrivee)) {
					Toast.makeText(getActivity(), "Selectionner deux villes differentes", Toast.LENGTH_SHORT).show();
				} else
					new GetHoraires(depart, arrivee).execute();
			}
		});
		tra = (LinearLayout) view.findViewById(R.id.tra);
	}

	private class GetHoraires extends AsyncTask<Void, Void, Void> {

		ProgressDialog progress;
		String v1, v2, json;

		public GetHoraires(String a, String b) {
			v1 = a;
			v2 = b;
		}

		@Override
		protected void onPreExecute() {
			progress = ProgressDialog.show(getActivity(), "", "Chargement...", true);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				DefaultHttpClient client = new DefaultHttpClient();

				String link = "http://192.168.1.145:8080/TravelServer2/travelservice/findtrain/" + v1 + "/" + v2;
				System.out.println(link);
				HttpGet post = new HttpGet(link);

				HttpResponse resp = client.execute(post);

				HttpEntity entity = resp.getEntity();
				InputStream ws = entity.getContent();

				BufferedReader r = new BufferedReader(new InputStreamReader(ws, "iso-8859-1"), 8);
				StringBuilder b = new StringBuilder();
				String line = null;
				while ((line = r.readLine()) != null) {
					b.append(line + "\n");
				}

				ws.close();
				json = b.toString();

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			try {
				JSONObject jsonObject = new JSONObject(json);
				JSONObject header = jsonObject.getJSONObject("header");
				if (header.getString("status").equals("OK")) {
					JSONObject jsonObject2 = jsonObject.getJSONObject("response");
					((LinearLayout) view.findViewById(R.id.select)).setVisibility(View.GONE);
					((LinearLayout) view.findViewById(R.id.content)).setVisibility(View.VISIBLE);
					((TextView) view.findViewById(R.id.titre)).setText("Trajet: " + depart + " -> " + arrivee);

					JSONArray horairestrain = jsonObject2.getJSONArray("horairesTrain");
					for (int i = 0; i < horairestrain.length(); i++) {
						JSONObject jsonObject3 = horairestrain.getJSONObject(i);
						View v = LayoutInflater.from(getActivity()).inflate(R.layout.train, null);
						((TextView) v.findViewById(R.id.dep)).setText(jsonObject3.getString("heureDepart"));
						((TextView) v.findViewById(R.id.arr)).setText(jsonObject3.getString("heureArrivee"));
						String cor = jsonObject3.getString("correspondence");
						if (cor.equals("null")) {
							cor = "-";
						}
						((TextView) v.findViewById(R.id.corr)).setText(cor);
						tra.addView(v);
					}

				} else {
					((TextView) view.findViewById(R.id.msg)).setVisibility(View.VISIBLE);
					((TextView) view.findViewById(R.id.msg)).setText(header.getString("message"));
				}
			} catch (Exception e) {
				Toast.makeText(getActivity(), "Une erreur s'est produite", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}

			if (progress.isShowing())
				progress.dismiss();
			super.onPostExecute(result);
		}
	}

	private class MyAdapter extends BaseAdapter implements SpinnerAdapter {

		/**
		 * The internal data (the ArrayList with the Objects).
		 */
		private final List<String> data;

		public MyAdapter(List<String> data) {
			this.data = data;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int i) {
			return i;
		}

		@Override
		public View getView(int position, View recycle, ViewGroup parent) {
			TextView text;
			if (recycle != null) {
				// Re-use the recycled view here!
				text = (TextView) recycle;
			} else {
				// No recycled view, inflate the "original" from the platform:
				text = (TextView) getActivity().getLayoutInflater().inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
			}
			text.setTextColor(Color.BLACK);
			text.setText(data.get(position));
			return text;
		}

	}

}
